package com.example.boot1;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class JVMDemo {
    public static void main(String[] args) {
        //testJVMParam();
        //testOOM2();
        //testOOM1();
        //testJVM参数();
        testDirectMemory1();
    }
    public static void testDirectMemory1(){
        //-Xms10m -Xmx10m -XX:+PrintGCDetails -XX:MaxDirectMemorySize=5m
        //jvm能碰到的内存
        System.out.println("配置的maxDirectMemory:"+(sun.misc.VM.maxDirectMemory()/(double)1024/1024)+"MB");

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        ByteBuffer bb = ByteBuffer.allocateDirect(6*1024* 1024);
    }
    public static void testDirectMemory(){
        //-Xms10m -Xmx10m -XX:+PrintGCDetails -XX:MaxDirectMemorySize=5m
        int i=0;
        List<String> list = new ArrayList<>();

        try {
            while(true){
                list.add(String.valueOf(++i).intern());
            }
        } catch (Throwable e) {
            System.out.println("***********i:"+i);
            e.printStackTrace();
            throw e;
        }
    }
    public static void testJVM参数(){
        System.out.println("-----helloGC-----");
        try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}
    }
    public static void testOOM2(){
        //需要配置idea中配置堆参数为10m
        byte[] bytes = new byte[40* 1024 * 1024];
        //Exception in thread in "main". java.land.OutOfMemoryError: Java heap space
    }
    public static void testOOM1(){
        //需要配置idea中配置堆参数为10m
        String str = "西安软件开发";
        while(true){
            str += str + new Random().nextInt(88888888)+new Random().nextInt(99999999);
        }
        //Exception in thread in "main". java.land.OutOfMemoryError: Java heap space
    }
    public static void testJVMParam(){
        //返回线程试图使用的最大内存
        long maxMemory = Runtime.getRuntime().maxMemory();
        //返回java虚拟机的内存总量
        long totalMemory = Runtime.getRuntime().totalMemory();
        System.out.println("-Xmx:MAX_MEMORY = "+maxMemory+" (字节) 、"+(maxMemory/(double)1024/ 1024)+"MB");
        System.out.println("-Xms:TOTAL_MEMORY = "+totalMemory+" (字节)、"+(totalMemory/(double)1024/1024)+"MB");
    }
    public static void testClassLoad(){
        Object object = new Object();
        System.out.println(object.getClass().getClassLoader());
        System.out.println("------------");
        JVMDemo jvmDemo = new JVMDemo();
        System.out.println(jvmDemo.getClass().getClassLoader());
    }
}
